package devcontainer

import (
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	devcontainer_api_service "code.gitea.io/gitea/services/devstar_devcontainer/api_services"
	devcontainer_service_options "code.gitea.io/gitea/services/devstar_devcontainer/options"
	"strconv"
)

// DeleteRepoDevcontainer 删除某仓库的 DevContainer
//
// DELETE /api/devcontainer
// 请求体参数：
// -- repoId: 需要为哪个仓库创建 DevContainer
// 注意：必须携带 用户登录凭证
func DeleteRepoDevcontainer(ctx *gitea_web_context.Context) {
	// 1. 检查用户登录状态，若未登录则返回未授权错误
	if ctx == nil || ctx.Doer == nil {
		Result.RespUnauthorizedFailure.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 取得参数 repoId
	repoIdStr := ctx.FormString("repoId")
	repoId, err := strconv.ParseInt(repoIdStr, 10, 64)
	if err != nil || repoId <= 0 {
		Result.RespFailedIllegalParams.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 3. 调用 API Service 层，删除 DevContainer
	opts := &devcontainer_service_options.AbstractDeleteDevcontainerOptions{
		Actor:  ctx.Doer,
		RepoId: repoId,
	}
	err = devcontainer_api_service.DeleteDevcontainerAPIService(ctx, opts)
	if err != nil {
		failureDeleteDevcontainer := Result.ResultType{
			Code: Result.RespFailedDeleteDevcontainer.Code,
			Msg:  Result.RespFailedDeleteDevcontainer.Msg,
			Data: map[string]any{
				"ErrorMsg": err.Error(),
			},
		}
		failureDeleteDevcontainer.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 4. 删除成功，返回提示信息
	Result.RespSuccess.RespondJson2HttpResponseWriter(ctx.Resp)
}
